package org.jeeasy.common.core.config;

import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author AlpsDDJ
 * @date 2020/11/10
 */
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(value = "jeeasy.cors.enable", havingValue = "true")
@EnableConfigurationProperties({CorsConfig.CorsConfiguration.class})
public class CorsConfig implements WebMvcConfigurer {

    private final CorsConfiguration corsConfiguration;

    @Override
    public void addCorsMappings(@NonNull CorsRegistry registry) {
        if (corsConfiguration.enable) {
            registry.addMapping(corsConfiguration.mapping)
                    .allowedOriginPatterns(corsConfiguration.allowedOrigins)
                    .allowedMethods(corsConfiguration.allowedMethods)
                    .maxAge(corsConfiguration.maxAge)
                    .allowedHeaders(corsConfiguration.allowedHeaders)
                    .allowCredentials(corsConfiguration.allowCredentials);
        }
    }

    @Data
    @ConfigurationProperties(prefix = "jeeasy.cors")
    public static class CorsConfiguration {
        private boolean enable = false;
        private final String mapping = "/**";
        private final String allowedOrigins = "*";
        private final String[] allowedMethods = new String[]{"POST", "GET", "PUT", "OPTIONS", "DELETE"};
        private final Long maxAge = 168000L;
        private final String allowedHeaders = "*";
        private final Boolean allowCredentials = true;

    }
}
